import React, { PropTypes, Component } from 'react'
import fetch from 'isomorphic-fetch'
import { Link } from 'react-router'
import InputWithLabel from './InputWithLabel'
import CheckboxInput from './CheckboxInput'
import TextInput from './TextInput'
import TextareaInput from './TextareaInput'
import SelectInput from './SelectInput'
import Layers from './Layers'
import Table from './Table'
import NavLink from './NavLink'
import style from './addStore.css'

import { myAjax, ROOTURL_MALL } from '../publicAPI/publicAPI'

class MallProductTypeEditor extends Component {
	constructor (props, context) {
	    super(props, context)
	    console.log("初始化");
	   
	    this.state = {	
	    	hasBeenMounted: false,
	        delete: false,
	        deleteId: -1,
	        status:1,//2修改，1新增
	        typeName:'',

	        disabled:false,
	        submitBtn:'block',
	        modifyBtn:'none',
	        deleteBtn:'none',
	    } ;// 初始化状态

	}

	componentWillMount() {
	     console.log("将安装");

	     if (this.props.params.id != undefined) {
	         //    根据参数获取数据
	         
	         console.log('-----',this.props.params.id);
	         this.setState({
	         	disabled:true,
	           submitBtn:'none',
	           modifyBtn:'block',
	           deleteBtn:'block',

	         });

	         if (!this.state.hasBeenMounted && this.props.params.id){
	             console.log('set finished');
	             this.handleGetInfo();
	         }
	     }else{
	         this.setState({
	         	disabled:false,
	           submitBtn:'block',
	           modifyBtn:'none',
	           deleteBtn:'none',

	         });
	     }
	}

	handleGetInfo(){
		var URL = ROOTURL_MALL + 'kabuy/category/instance.api';
		var _this = this;
		var param = {
			id: this.props.params.id
		};
		fetch(URL,{
		    method: 'POST',
		    mode: "cors",
		    body: JSON.stringify(param)
		}).then(function (res) {
		    	if(res.ok){
		    	    res.json().then(data=>{
		    	        console.log(data);
		    	            _this.setState({
		    	                typeName: data.name,
		    	            })
		    	        console.log(_this.state)
		    	    })
		    	}
		});
	}

	componentDidMount() {
	    console.log("安装成功");  
	}

	handleSubmit(e){
		var URL = ROOTURL_MALL + 'kabuy/category/instance.api';
		if(this.state.status == 1){
			var param = {
				name: this.state.typeName,
				dd: false
			};

			fetch(URL,{
			    method: 'POST',
			    mode: 'cors',
			    body: JSON.stringify(param)
			}).then(function (res) {
			    if (res.ok){
			    	alert('添加成功！');
			        window.location.href="/MallProductTypeM";
			    }else{
			        alert('添加失败！可能有重名了！');
			    }
			});
		}else if(this.state.status == 2){
			var param = {
				name: this.state.typeName,
				id: this.props.params.id
			};

			fetch(URL,{
			    method: 'POST',
			    mode: 'cors',
			    body: JSON.stringify(param)
			}).then(function (res) {
			    if (res.ok){
			    	alert('修改成功！');
			        window.location.href="/MallProductTypeM";
			    }else{
			        alert('修改失败！可能有重名了！');
			    }
			});
		}
		
	}

	handleModify(e){
		this.setState({
			disabled:false,
			submitBtn:'block',
			modifyBtn:'none',
			deleteBtn:'none',
			status:2
		})
	}

	handleDelete(id){
		this.setState({
			delete: !this.state.delete,
			deleteId: id
		})
	}

	deleteType(){
		var _this = this;
		var param = {
		  // id:this.state.deleteId
		}
		   var URL1 = ROOTURL_MALL + 'kabuy/category/instance.api?id=' + this.state.deleteId;
		   fetch(URL1,{
		       method: 'DELETE',
		       mode: "cors",
		       body: param
		   }).then(function (res) {
		       if (res.ok){
		           console.log('delete success');
		           window.location.href="/MallProductTypeM";
		       }else{
		           console.log(res)
		       }
		   });
		   this.setState({
		       delete: !this.state.delete
		   });
	}

	render(){
		return (

			<div className="right-wapper ">
			    <div className="rt-wrap" style={{border:'none'}}>
			        <div className="right-wrap">
			            <div className="wrap" style={{paddingBottom:"40px"}}>
			                <div className={style["input_div"]} style={{margin:'20px 0 40px'}}>
			                    <label>名称</label>
			                    <TextInput inputId="typeName"  disabled={this.state.disabled} placeHolder="请输入分类名称" val={this.state.typeName} onChange={val=>this.setState(Object.assign({}, this.state, {typeName: val}))}/>&nbsp;&nbsp;
			                     <span style={{marginBottom:'20px',marginLeft:'2px',color:'red'}}>{this.state.errorM}</span>
			                </div>
			                <span id="hint"/>
			                <button id="submit" className={style["main_btn"]} onClick={(e) => this.handleSubmit(e) }  style={{backgroundColor: '#2285c7',float:'left',border: '1px solid #1e77b3',display: this.state.submitBtn}}>保存</button>
			                <button id="modify" className={style["main_btn"]} style={{backgroundColor: '#2285c7',float:'left',border: '1px solid #1e77b3',display: this.state.modifyBtn,marginLeft:'12px'} } onClick={  (e) => this.handleModify(e) }>修改</button>
			                <button id="delete" className={style["main_btn"]} style={{backgroundColor: '#f2846f',float:'left',border: '1px solid #d55c44',display: this.state.deleteBtn,marginLeft:'12px'} } onClick={ (e) =>this.handleDelete(this.props.params.id) }>删除</button>
			                
			                <Link to={`/MallProductTypeM`}>
			                     <button id="back" className={style["main_btn"]}  style={{backgroundColor: '#2285c7',border: '1px solid #1e77b3',marginLeft:'12px'}}>返回</button>
			                </Link>
			            </div>
			        </div>
			    </div>
			    { this.state.delete ?
			      <div id={style.msgDialog}>
			        <div className={style['msgDialog_div']}><h3 id={style['msgDialog_title']}>删除提示？</h3><p id={style['msgDialog_content']}>确认删除？</p>
			          <div className={style['msgDialog_button']}>
			            <button id={style['msgDialog_yes']} onClick={this.deleteType.bind(this)}>确定</button>
			            <button id={style['msgDialog_no']} onClick={()=>this.setState({delete: !this.state.delete})}>取消</button>
			          </div>
			        </div>
			      </div> : null}
			</div>
		)
	}
}


export default MallProductTypeEditor